<template>
  <div class="ultimate-tic-tac-toe-game">
    <!-- 背景特效 -->
    <div class="particles-background"></div>

    <!-- 移动端顶部导航 -->
    <div class="mobile-header" v-if="isMobile">
      <el-button :icon="iconMenu" @click="toggleMenu" class="menu-btn"></el-button>
      <h2 class="app-title">超级井字棋</h2>
    </div>

    <!-- 主网格布局 -->
    <div class="grid-container">
      <!-- 用户信息区域（移动端侧边菜单） -->
      <div class="user-panel" :class="{'mobile-active': showMenu}">
        <UserProfile />
        <div class="mobile-menu-items" v-if="isMobile">
          <button @click="activePanel = 'game'; showMenu = false">
            <i class="icon-game"></i> 游戏
          </button>
          <button @click="activePanel = 'chat'; showMenu = false">
            <i class="icon-chat"></i> 聊天
          </button>
          <button @click="activePanel = 'status'; showMenu = false">
            <i class="icon-info"></i> 状态
          </button>
        </div>
      </div>

      <!-- 游戏主区域（桌面端和移动端主内容） -->
      <div class="game-panel" v-if="!isMobile || activePanel === 'game'">
        <div class="panel-header">
          <div class="header-left">
            <h2 class="game-title">
              <i class="icon-game"></i>
              超级井字棋
            </h2>
            <div class="game-info-display">
              <div class="room-id-card">
                <span class="room-id-label">房间ID:</span>
                <span class="room-id-value">{{ roomId }}</span>
              </div>
              <div class="player-turn-badge" :class="{ 'your-turn': isYourTurn }">
                <i class="icon-turn"></i>
                {{ turnStatusText }}
              </div>
            </div>
          </div>
          <div class="header-right">
            <div class="connection-status" :class="{ connected: isConnected }">
              <span class="status-dot"></span>
              {{ isConnected ? '已连接' : '连接中...' }}
            </div>
          </div>
        </div>

        <!-- 超级井字棋主棋盘 -->
        <div class="ultimate-board" :class="{ 'is-first-move': isFirstMove, 'highlight-ultimateboard': highlightUltimateBoard }">
          <div
              v-for="(smallBoard, boardIndex) in ultimateBoard"
              :key="boardIndex"
              class="small-board"
              :class="{
              'active-board': isActiveBoard(boardIndex),
              'won-board-x': smallBoard.winner === 'X',
              'won-board-o': smallBoard.winner === 'O',
              'highlight-board': highlightedBoards.includes(boardIndex)
            }"
          >
            <div
                v-for="(cell, cellIndex) in smallBoard.cells.flat()"
                :key="cellIndex"
                class="cell"
                :class="{
                'x-cell': cell === 'X',
                'o-cell': cell === 'O',
                'disabled': canMakeMove(boardIndex, cellIndex) === false,
              }"
                @click="makeMove(boardIndex, cellIndex)"
                @mouseenter="handleNextStepHighlight(cellIndex)"
                @mouseleave="clearNextStepHighlights"
            >
              <span class="cell-content">{{ cell }}</span>
            </div>
          </div>
        </div>

        <div class="game-actions">
          <button
              @click="leaveGame"
              class="btn-leave"
          >
            离开游戏
          </button>
          <button
              @click="resetGame"
              class="btn-reset"
          >
            重新开始
          </button>
          <button
              class="btn-rules"
              @click="showRules = true"
          >
            游戏规则
          </button>
        </div>
      </div>

      <!-- 聊天区域（桌面端和移动端切换显示） -->
      <div class="chat-panel" v-if="!isMobile || activePanel === 'chat'">
        <ChatWindow />
      </div>

      <!-- 游戏状态区域（桌面端和移动端切换显示） -->
      <div class="status-panel" v-if="!isMobile || activePanel === 'status'">
        <div class="status-card">
          <h3 class="status-title">游戏状态</h3>
          <div class="status-content">
            <div class="status-item">
              <span class="status-label">当前回合:</span>
              <span class="status-value">{{ currentPlayerName }}</span>
            </div>
            <div class="status-item">
              <span class="status-label">你的符号:</span>
              <span class="status-value" :class="playerSymbol === 'O' ? 'x-text' : 'o-text'">
                {{ playerSymbol }}
              </span>
            </div>
            <div class="status-item">
              <span class="status-label">游戏状态:</span>
              <span class="status-value" :class="gameStatusClass">
                {{ gameStatusText }}
              </span>
            </div>
            <div class="status-item" v-if="activeBoard">
              <span class="status-label">当前棋盘:</span>
              <span class="status-value">
                ({{ Math.floor(activeBoard / 3) + 1 }}, {{ (activeBoard % 3) + 1 }})
              </span>
            </div>
          </div>
        </div>
        <div class="players-card">
          <h3 class="players-title">玩家列表</h3>
          <div class="players-list">
            <div
                v-for="player in players"
                :key="player.id"
                class="player-item"
                :class="{
                'current-player': player.id === currentPlayerId,
                'you': player.id === userId
              }"
            >
              <span class="player-symbol" :class="player.id === userId ?
                (playerSymbol === 'X' ? 'x-text' : 'o-text') :
                (playerSymbol === 'X' ? 'o-text' : 'x-text')">
                {{ player.id === userId ? playerSymbol : opponentSymbol }}
              </span>
              <span class="player-name">{{ player.username }}</span>
              <span v-if="player.id === hostId" class="host-badge">房主</span>
              <span v-if="player.id === userId" class="you-badge">你</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 游戏规则弹窗 -->
    <el-dialog v-model="showRules" title="超级井字棋规则" width="80%">
      <div class="rules-content">
        <h3>基本规则：</h3>
        <ol>
          <li>游戏在一个3×3的大棋盘中进行，每个大格子又是一个3×3的小棋盘</li>
          <li>游戏开始由X玩家先手，可以在任意小棋盘的任意位置落子</li>
          <li>你的落子位置决定了对手必须在哪个小棋盘落子：
            <ul>
              <li>例如你在小棋盘(2,3)的第(1,1)格落子，对手必须在大棋盘(1,1)对应的小棋盘内落子</li>
            </ul>
          </li>
          <li>如果指定的小棋盘已分出胜负或已满，对手可以在任意未完成的小棋盘落子</li>
          <li>在小棋盘内先连成一条直线(横、竖或对角)的玩家赢得该小棋盘</li>
          <li>在大棋盘上先连成一条直线的玩家赢得整局游戏</li>
          <li>如果所有小棋盘都完成但大棋盘未分胜负，则为平局</li>
        </ol>

        <h3>策略提示：</h3>
        <ul>
          <li>不仅要考虑当前小棋盘的布局，还要考虑如何引导对手到对你有利的小棋盘</li>
          <li>有时需要放弃一个小棋盘的胜利，以获得更大的战略优势</li>
          <li>注意观察对手的意图，防止被引导到对手已经布局好的小棋盘</li>
        </ul>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import UserProfile from '../../homeView/components/UserProfile.vue'
import ChatWindow from '../../homeView/components/ChatWindow.vue'
import {ElMessage, ElDialog, ElMessageBox} from 'element-plus'
import config from '@/config.js'
import {useRoom} from "@/views/homeView/composables/useRoom.js";
import {useRoomStore} from "@/stores/room.js";
import {Menu} from "@element-plus/icons-vue";

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const roomStore = useRoomStore()

// 游戏状态
const ultimateBoard = ref(
    Array(9).fill().map(() => ({
      winner: null,
      cells: Array(3).fill().map(() => Array(3).fill(''))
    }))
)
const currentPlayerId = ref(null)
const winnerId = ref(null)
const gameOver = ref(false)
const isConnected = ref(false)
const activeBoard = ref(null) // 当前需要下棋的小棋盘索引
const showRules = ref(false)
const gameState = ref({
  ultimateWinner: null,
  gameOver: false
})
const isFirstMove = ref(true) // 是否首步
const forbiddenFirstBoard = 4 // 禁止首步的棋盘索引（中间棋盘）
const highlightedBoards = ref([]) // 高亮显示的棋盘索引
const highlightUltimateBoard = ref(false) // 高亮显示最外层棋盘

// 玩家信息
const userId = computed(() => userStore.userId)
const username = computed(() => userStore.username)
const roomId = ref(useRoom().roomId)
const playerSymbol = ref(null)
const opponentSymbol = ref(null)
const opponentId = ref(null)
const hostId = ref(null)
const players = ref([])

// WebSocket 连接
const socket = ref(null)

// 移动端相关状态
const showMenu = ref(false)
const activePanel = ref('game')
const windowWidth = ref(window.innerWidth)
const iconMenu = Menu

const isMobile = computed(() => windowWidth.value < 768)

const toggleMenu = () => {
  showMenu.value = !showMenu.value
}

const handleResize = () => {
  windowWidth.value = window.innerWidth
  if (windowWidth.value >= 768) {
    showMenu.value = false
  }
}

// 计算属性
const isHost = computed(() => userId.value === hostId.value)
const isYourTurn = computed(() => currentPlayerId.value === userId.value && !gameOver.value)
const opponentName = computed(() => {
  const opponent = players.value.find(p => p.id !== userId.value)
  return opponent?.username || '等待对手'
})

// 检查是否是当前玩家的回合
const currentPlayerName = computed(() => {
  if (gameOver.value) return '游戏结束'
  return currentPlayerId.value === userId.value ? '你的回合' : `${opponentName.value}的回合`
})

const turnStatusText = computed(() => {
  if (gameOver.value) return '游戏结束'
  return isYourTurn.value ? '轮到你了' : '对手回合'
})

const gameStatusText = computed(() => {
  if (!currentPlayerId.value) return '等待游戏开始...'
  if (gameOver.value) {
    if (!winnerId.value) return '平局!'
    return winnerId.value === userId.value ? '你赢了!' : '你输了!'
  }
  return isYourTurn.value ? '你的回合' : '对手回合'
})

const gameStatusClass = computed(() => {
  if (gameOver.value) {
    return winnerId.value === userId.value ? 'win-text' :
        winnerId.value ? 'lose-text' : 'draw-text'
  }
  return isYourTurn.value ? 'your-turn-text' : 'opponent-turn-text'
})

// 检查是否是当前活跃的小棋盘
const isActiveBoard = (boardIndex) => {
  return !gameOver.value &&
      isYourTurn.value &&
      (activeBoard.value === null || activeBoard.value === boardIndex) &&
      !ultimateBoard.value[boardIndex].winner
}

// 检查是否可以下棋
const canMakeMove = (boardIndex, cellIndex) => {
  // console.log('当前棋盘:', boardIndex, '当前格子:', cellIndex);
  if (gameOver.value || !isYourTurn.value) {
    // console.log('游戏已结束或不是你的回合');
    return false;
  }

  if (isFirstMove.value && boardIndex === forbiddenFirstBoard) {
    // console.log('首步禁止在此棋盘落子');
    return false;
  }

  if (activeBoard.value !== null && activeBoard.value !== boardIndex) {
    // console.log('当前活跃棋盘:', activeBoard.value, '与当前棋盘:', boardIndex, '不匹配');
    return false;
  }

  if (ultimateBoard.value[boardIndex].winner) {
    // console.log('小棋盘已满或有胜负');
    return false;
  }

  const row = Math.floor(cellIndex / 3);
  const col = cellIndex % 3;
  const canMove = ultimateBoard.value[boardIndex].cells[row][col] === null ||
      ultimateBoard.value[boardIndex].cells[row][col] === '';
  // console.log('当前格子状态:', ultimateBoard.value[boardIndex].cells[row][col], '可以下棋:', canMove);
  return canMove;
}
// const canMakeMove = (boardIndex, cellIndex) => {
//   if (gameOver.value || !isYourTurn.value) return false;
//
//   // 如果有活跃棋盘限制，且当前棋盘已满或有胜负
//   if (activeBoard.value !== null && (ultimateBoard.value[activeBoard.value].winner || isSmallBoardFull(activeBoard.value))) {
//     return !ultimateBoard.value[boardIndex].winner && !isSmallBoardFull(boardIndex);
//   }
//
//   // 如果有活跃棋盘限制，且不是当前棋盘
//   if (activeBoard.value !== null && activeBoard.value !== boardIndex) return false;
//
//   // 如果小棋盘已有胜负
//   if (ultimateBoard.value[boardIndex].winner) return false;
//
//   const row = Math.floor(cellIndex / 3);
//   const col = cellIndex % 3;
//   return ultimateBoard.value[boardIndex].cells[row][col] === '';
// };
// 初始化WebSocket连接
const initWebSocket = () => {
  const wsUrl = `${config.apiWsUrl}/ws/UltimateTicTacToe`
  socket.value = new WebSocket(wsUrl)

  socket.value.onopen = () => {
    console.log('WebSocket连接已建立')
    isConnected.value = true
    // 发送设置用户ID的消息
    socket.value.send(JSON.stringify({
      type: 'setId',
      userId: localStorage.getItem('userId'),
    }))
    // socket.value.send(JSON.stringify({
    //   type: 'startGame',
    //   roomId: roomId.value,
    //   playerList: players.value
    // }))
    console.log(localStorage.getItem('isStarted'))

    if(localStorage.getItem('isStarted') === null || localStorage.getItem('isStarted') === 'false') {
      socket.value.send(JSON.stringify({
        type: 'startGame',
        roomId: roomId.value,
        playerList: players.value
      }))
      localStorage.setItem('isStarted', true)
    }else if(localStorage.getItem('isStarted') === 'true') {
      console.log('恢复游戏')
      socket.value.send(JSON.stringify({
        type: 'restoreSession',
        userId: localStorage.getItem('userId'),
        roomId: localStorage.getItem('currentRoomId'),
      }));
    }



  }

  socket.value.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data)
      console.log('收到消息:', data)
      handleMessage(data)
    } catch (e) {
      console.error('消息解析错误:', e)
    }
  }

  socket.value.onclose = () => {
    console.log('WebSocket连接已关闭')
    isConnected.value = false
    if (!gameOver.value) {
      ElMessage.error('连接已断开')
      router.push('/home')
      localStorage.removeItem('isStarted')

    }
  }

  socket.value.onerror = (error) => {
    console.error('WebSocket错误:', error)
    isConnected.value = false
    ElMessage.error('连接服务器失败')
  }
}

// 处理收到的消息
const handleMessage = (data) => {
  switch (data.type) {
    case 'startGame':
      handleStartGame(data)
      break
    case 'newStep':
      handleNewStep(data)
      break
    case 'endGame':
      handleEndGame(data)
      break
    case 'playerLeave':
      handlePlayerLeave(data)
      break
    case 'sessionRestored':
      handleRestoredSession(data)
      break
    default:
      console.log('未知消息类型:', data.type)
  }
}

// 处理游戏开始
const handleStartGame = (data) => {

  players.value = data.playerList
  currentPlayerId.value = data.firstPlayerId
  isFirstMove.value = true
  // 确定自己和对手
  const me = data.playerList.find(p => p.id === userId.value)
  const opponent = data.playerList.find(p => p.id !== userId.value)
  opponentId.value = opponent?.id || null

  // 确定房主
  hostId.value = data.playerList[0].id

  // 分配符号 (先手是X)
  playerSymbol.value = currentPlayerId.value === userId.value ? 'X' : 'O'
  opponentSymbol.value = currentPlayerId.value === userId.value ? 'O' : 'X'
  console.log('玩家:', players.value,playerSymbol.value)

  // 重置游戏状态
  ultimateBoard.value = Array(9).fill().map(() => ({
    winner: null,
    cells: Array(3).fill().map(() => Array(3).fill(''))
  }))
  winnerId.value = null
  gameOver.value = false
  activeBoard.value = null

}

// 处理新步骤
const handleNewStep = (data) => {
  const [boardRow, boardCol, cellRow, cellCol] = data.move.split(',').map(Number)
  const boardIndex = boardRow * 3 + boardCol

  // 确定下棋的符号
  console.log('下棋的符号:', data.currentPlayerId, userId.value)
  const symbol = data.currentPlayerId === userId.value ? playerSymbol.value : opponentSymbol.value
  ultimateBoard.value[boardIndex].cells[cellRow][cellCol] = symbol

  // 更新首步状态
  if (isFirstMove.value) {
    isFirstMove.value = false
  }

  // 检查小棋盘是否有胜负
  checkSmallBoardWinner(boardIndex)

  // 检查大棋盘是否有胜负
  checkUltimateWinner()

  // 检查游戏是否结束
  console.log('胜利者:', gameState.ultimateWinner)
  if(gameState.gameOver) {
    socket.value.send(
        JSON.stringify({
          type: 'endGame',
          roomId: roomId.value,
          winnerId: gameState.ultimateWinner === 'draw' ? null : gameState.ultimateWinner
        })
    )
  }
  // 更新当前玩家
  currentPlayerId.value = data.nextPlayerId
  //如果下一个活跃棋盘没有被占领或已满，则设置为下一个活跃棋盘 否则可以随意下棋
  // 设置下一个活跃棋盘
  activeBoard.value = data.nextBoard === -1 ? null : data.nextBoard

  // 重新渲染游戏并更新UI
  updateUI()

}

// 处理游戏结束
const handleEndGame = (data) => {
  winnerId.value = data.winnerId
  gameOver.value = true
  switch (data.winnerId){
    case userId.value:
      ElMessage.success("你赢了!")
        ElMessageBox.confirm('你赢了!', '提示', {
        confirmButtonText: '继续',
        type: 'success',
        showClose: false,
        })
      break
    case opponentId.value:
      ElMessage.error("你输了!")
      ElMessageBox.confirm('你输了!', '提示', {
        confirmButtonText: '继续',
        type: 'error',
        showClose: false,
        })
      break
    case null:
      ElMessage.warning("平局!")
      ElMessageBox.confirm('平局!', '提示', {
        confirmButtonText: '继续',
        type: 'warning',
        showClose: false,
        })
      break
  }
}

// 处理玩家离开
const handlePlayerLeave = (data) => {
  const playerId = data.playerId
  // players.value = players.value.filter(player => player.id !== playerId)
  console.log('玩家离开:', playerId, '当前玩家:', userId.value, '对手:', opponentId.value, '房主:', hostId.value)
  if (playerId === userId.value) {
    ElMessage.warning('你已离开游戏')
  } else {
    ElMessage.warning('对手已离开游戏')
  }
  router.push('/home')
  localStorage.removeItem('isStarted')
}


const handleRestoredSession = (data) => {
  // 更新玩家列表
  players.value = data.playerList

  // 更新当前玩家
  currentPlayerId.value = data.currentPlayerId

  // 更新活跃棋盘
  activeBoard.value = data.activeBoard

  // 更新棋盘状态
  for (let boardIndex = 0; boardIndex < 9; boardIndex++) {
    // 更新小棋盘状态
    ultimateBoard.value[boardIndex].cells = data.boardState[boardIndex]

    // 更新小棋盘胜负状态
    ultimateBoard.value[boardIndex].winner = data.smallBoardWinners[boardIndex]
  }

  const firstPlayerId = data.firstPlayerId
  // 确定玩家符号
  const me = players.value.find(p => p.id === userId.value)
  const opponent = players.value.find(p => p.id !== userId.value)
  if (me && opponent) {
    playerSymbol.value = firstPlayerId === userId.value ? 'X' : 'O'
    opponentSymbol.value = playerSymbol.value === 'X' ? 'O' : 'X'
    opponentId.value = opponent.id
  }

  // 更新游戏状态
  gameOver.value = false
  isFirstMove.value = data.isFirstMove

  ElMessage.success('游戏状态已恢复')
}
const findUserIdBySymbol= (symbol) => {
  if(symbol=== playerSymbol.value) {
    return userId.value
  } else {
    return opponentId.value
  }
}

// 检查小棋盘是否有胜负
const checkSmallBoardWinner = (boardIndex) => {
  const board = ultimateBoard.value[boardIndex]
  const cells = board.cells
  // 检查行
  for (let i = 0; i < 3; i++) {
    if (cells[i][0] &&
        cells[i][0] === cells[i][1] &&
        cells[i][0] === cells[i][2]) {
      board.winner = cells[i][0]
      ultimateBoard.value[boardIndex].winner = cells[i][0]
      return "win"
    }
  }

  // 检查列
  for (let j = 0; j < 3; j++) {
    if (cells[0][j] &&
        cells[0][j] === cells[1][j] &&
        cells[0][j] === cells[2][j]) {
      board.winner = cells[0][j]
      ultimateBoard.value[boardIndex].winner = cells[0][j]
      return "win"
    }
  }

  // 检查对角线
  if (cells[0][0] &&
      cells[0][0] === cells[1][1] &&
      cells[0][0] === cells[2][2]) {
    board.winner = cells[0][0]
    ultimateBoard.value[boardIndex].winner = cells[0][0]
    return "win"
  }

  if (cells[0][2] &&
      cells[0][2] === cells[1][1] &&
      cells[0][2] === cells[2][0]) {
    board.winner = cells[0][2]
    ultimateBoard.value[boardIndex].winner = cells[0][2]
    return "win"
  }

  // 检查是否平局
  if (isSmallBoardFull(boardIndex)) {
    board.winner = 'draw'
    ultimateBoard.value[boardIndex].winner = 'draw'
    return "draw"
  }

  console.log('检查小棋盘:', ultimateBoard.value[boardIndex])
}

// 检查小棋盘是否已满
const isSmallBoardFull = (boardIndex) => {
  return ultimateBoard.value[boardIndex].cells.every(row => row.every(cell => cell))
}

// 检查大棋盘是否有胜负
const checkUltimateWinner = () => {
  const winners = ultimateBoard.value.map(board => board.winner)

  // 检查行
  for (let i = 0; i < 3; i++) {
    const idx = i * 3
    if (winners[idx] && winners[idx] !== 'draw' &&
        winners[idx] === winners[idx + 1] &&
        winners[idx] === winners[idx + 2]) {
      gameState.ultimateWinner = findUserIdBySymbol(winners[idx])
      gameState.gameOver = true
      return
    }
  }

  // 检查列
  for (let j = 0; j < 3; j++) {
    if (winners[j] && winners[j] !== 'draw' &&
        winners[j] === winners[j + 3] &&
        winners[j] === winners[j + 6]) {
      gameState.ultimateWinner = findUserIdBySymbol(winners[j])
      gameState.gameOver = true
      return
    }
  }

  // 检查对角线
  if (winners[0] && winners[0] !== 'draw' &&
      winners[0] === winners[4] &&
      winners[0] === winners[8]) {
    gameState.ultimateWinner = findUserIdBySymbol(winners[0])
    gameState.gameOver = true
    return
  }

  if (winners[2] && winners[2] !== 'draw' &&
      winners[2] === winners[4] &&
      winners[2] === winners[6]) {
    gameState.ultimateWinner = findUserIdBySymbol(winners[2])
    gameState.gameOver = true
    return
  }

  // 检查是否平局
  if (winners.every(winner => winner) && !gameState.ultimateWinner) {
    gameState.ultimateWinner = 'draw'
    gameState.gameOver = true
  }

}

// 玩家下棋
const makeMove = (boardIndex, cellIndex) => {
  if (!canMakeMove(boardIndex, cellIndex)) return

  const boardRow = Math.floor(boardIndex / 3)
  const boardCol = boardIndex % 3
  const cellRow = Math.floor(cellIndex / 3)
  const cellCol = cellIndex % 3

  // 本地更新棋盘
  ultimateBoard.value[boardIndex].cells[cellRow][cellCol] = playerSymbol.value

  // 计算下一个需要下棋的棋盘
  const nextBoard = cellRow * 3 + cellCol
  // 检查下一个棋盘是否已被占领或已满
  let boardStatus = "default"
  boardStatus = checkSmallBoardWinner(nextBoard)
  console.log("boardStatus:",boardStatus)
  const isNextBoardAvailable = ultimateBoard.value[nextBoard].winner == null && !isSmallBoardFull(nextBoard)
  console.log(ultimateBoard.value[nextBoard].winner, isSmallBoardFull(nextBoard), isNextBoardAvailable)
  socket.value.send(JSON.stringify({
    type: 'newStep',
    roomId: roomId.value,
    playerId: userId.value,
    move: `${boardRow},${boardCol},${cellRow},${cellCol}`,
    nextBoard: isNextBoardAvailable ? nextBoard : -1
  }))


}

// 离开游戏
const leaveGame = () => {
  if (socket.value && socket.value.readyState === WebSocket.OPEN) {
    socket.value.send(JSON.stringify({
      type: 'leaveGame',
      roomId: roomId.value,
      playerId: userId.value
    }))
  }
  localStorage.removeItem('currentRoomId')
  localStorage.removeItem('isStarted')
}

// 重置游戏
const resetGame = () => {

  // if(players[0].userId !== userId.value) {
  //   ElMessage.warning('只有房主可以重置游戏')
  //   return
  // }
  localStorage.setItem('isStarted', 'false')
  socket.value.send(JSON.stringify({
    type: 'startGame',
    roomId: roomId.value,
    playerList: players.value
  }))

}

// 更新UI状态
const updateUI = () => {
  // 这里可以根据需要添加UI更新逻辑
}
const handleNextStepHighlight = (cellIndex) => {
  if (gameOver.value || !isYourTurn.value) return;

  // 获取当前悬停的棋盘索引
  const hoveredBoardIndex = Array.from(document.querySelectorAll('.small-board'))
      .findIndex(board => board.contains(event.target));
  if (hoveredBoardIndex === -1) return;

  // 清除之前的高亮
  clearNextStepHighlights();

  // 计算下一个棋盘索引
  const nextBoardRow = Math.floor(cellIndex / 3);
  const nextBoardCol = cellIndex % 3;
  const nextBoardIndex = nextBoardRow * 3 + nextBoardCol;

  // 检查是否有活跃棋盘限制
  if (activeBoard.value !== null && activeBoard.value !== hoveredBoardIndex) {
    return;
  }

  // 检查下一个棋盘是否可用
  const nextBoard = ultimateBoard.value[nextBoardIndex];
  const isNextBoardAvailable = nextBoard?.winner === null && !isSmallBoardFull(nextBoardIndex);

  // 确定要高亮的棋盘
  if (isNextBoardAvailable) {
    // 高亮下一个棋盘
    highlightedBoards.value = [nextBoardIndex];
  } else {
    // 高亮所有可用的棋盘
    // highlightedBoards.value = ultimateBoard.value
    //     .map((board, index) =>
    //         board.winner === null &&
    //         (activeBoard.value === null || activeBoard.value === index) ?
    //             index : -1
    //     )
    //     .filter(index => index !== -1);

    //高亮最外层大棋盘
    highlightUltimateBoard.value = true

  }
};

const clearNextStepHighlights = () => {
  highlightedBoards.value = [];
  highlightUltimateBoard.value = false
};
// 生命周期
onMounted(() => {

  const savedRoomId = localStorage.getItem('currentRoomId')
  console.log('savedRoomId:', savedRoomId)
  if (savedRoomId !== null) {
    useRoom().roomId.value = savedRoomId
    roomId.value = savedRoomId
    useRoomStore().roomId = savedRoomId
    console.log('恢复房间ID:', useRoomStore().roomId)
  }
  userId.value = userStore.userId
  players.value = useRoomStore().players
  initWebSocket()

  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  if (socket.value) {
    socket.value.close()
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.ultimate-tic-tac-toe-game {
  position: relative;
  overflow: hidden;
  height: 100vh;
  width: 100vw;
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
}

.particles-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  background-size: cover;
  opacity: 0.3;
}

/* 移动端顶部导航 */
.mobile-header {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  background: rgba(26, 26, 46, 0.9);
  backdrop-filter: blur(5px);
  z-index: 10;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.mobile-header .menu-btn {
  background: none;
  border: none;
  color: white;
  font-size: 24px;
  margin-right: 15px;
  padding: 5px;
}

.mobile-header .app-title {
  color: white;
  font-size: 18px;
  margin: 0;
}

.grid-container {
  display: grid;
  grid-template-columns: 300px 1fr 300px;
  grid-template-rows: auto 1fr;
  grid-template-areas:
    "user game chat"
    "user game status";
  gap: 20px;
  padding: 20px;
  height: 100%;
  position: relative;
  z-index: 1;
}

.user-panel {
  grid-area: user;
  background: rgba(26, 26, 46, 0.8);
  border-radius: 15px;
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.1);
  transition: transform 0.3s ease;
}

.game-panel {
  grid-area: game;
  background: rgba(22, 33, 62, 0.7);
  border-radius: 15px;
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.1);
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.chat-panel {
  grid-area: chat;
  background: rgba(26, 26, 46, 0.8);
  border-radius: 15px;
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  flex-direction: column;
  height: 350px;
  min-height: 350px;
  max-height: 350px;
  overflow: hidden;
}

.status-panel {
  grid-area: status;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  border-radius: 12px;
  background: rgba(76, 201, 240, 0.1);
  border: 1px solid rgba(76, 201, 240, 0.2);
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.game-title {
  margin: 0;
  font-size: 1.5rem;
  color: #4cc9f0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.icon-game {
  display: inline-block;
  width: 24px;
  height: 24px;
  background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%234cc9f0"><path d="M21 6H3c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-10 7H8v3H6v-3H3v-2h3V8h2v3h3v2zm4.5 2c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm4-3c-.83 0-1.5-.67-1.5-1.5S18.67 9 19.5 9s1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/></svg>') no-repeat center;
}

.game-info-display {
  display: flex;
  align-items: center;
  gap: 15px;
}

.room-id-card {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: rgba(26, 26, 46, 0.8);
  border-radius: 8px;
  border: 1px solid rgba(76, 201, 240, 0.3);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.room-id-label {
  font-size: 0.9rem;
  color: rgba(255, 255, 255, 0.7);
  margin-right: 8px;
}

.room-id-value {
  font-family: 'Courier New', monospace;
  font-size: 1.1rem;
  font-weight: bold;
  letter-spacing: 1px;
  color: #4cc9f0;
}

.player-turn-badge {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 0.9rem;
  gap: 6px;
  background: rgba(255, 193, 7, 0.2);
  color: #ffc107;
}

.player-turn-badge.your-turn {
  background: rgba(76, 175, 80, 0.2);
  color: #4caf50;
}

.icon-turn {
  display: inline-block;
  width: 16px;
  height: 16px;
  background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/></svg>') no-repeat center;
}

.connection-status {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 0.8rem;
  background: rgba(255, 107, 107, 0.2);
  color: #ff6b6b;
  gap: 6px;
}

.connection-status.connected {
  background: rgba(76, 201, 240, 0.2);
  color: #4cc9f0;
}

.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ff6b6b;
}

.connection-status.connected .status-dot {
  background: #4cc9f0;
  box-shadow: 0 0 8px #4cc9f0;
}

/* 超级井字棋棋盘样式 */
.ultimate-board {
  width: 80vw;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  gap: 10px;
  background-color: #2c3e50;
  padding: 10px;
  border-radius: 5px;
  margin: 0 auto;
  max-width: 30vw;
  aspect-ratio: 1/1;
}

.small-board {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  gap: 2px;
  background-color: #2c3e50;
  padding: 5px;
  border-radius: 3px;
}

.small-board.active-board {
  box-shadow: 0 0 0 3px #f39c12;
}

.small-board.won-board-x {
  background-color: rgb(231, 76, 60);
}

.small-board.won-board-o {
  background-color: rgb(52, 152, 219);
}

.cell {
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  aspect-ratio: 1;
  transition: all 0.2s;
}

.cell:hover {
  background-color: #f1f1f1;
}

.cell.disabled {
  cursor: not-allowed;
  opacity: 0.7;
}

.x-cell {
  color: #e74c3c;
}

.o-cell {
  color: #3498db;
}

.cell-content {
  font-size: 1.5rem;
}

.game-actions {
  display: flex;
  gap: 15px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  justify-content: center;
}

.btn-leave, .btn-reset, .btn-rules {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-leave {
  background: rgba(255, 107, 107, 0.2);
  color: #ff6b6b;
}

.btn-leave:hover {
  background: rgba(255, 107, 107, 0.3);
  transform: translateY(-2px);
}

.btn-reset {
  background: linear-gradient(90deg, #6a11cb 0%, #2575fc 100%);
  color: white;
}

.btn-reset:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(106, 17, 203, 0.4);
}

.btn-rules {
  background: rgba(46, 204, 113, 0.2);
  color: #2ecc71;
}

.btn-rules:hover {
  background: rgba(46, 204, 113, 0.3);
  transform: translateY(-2px);
}

.status-card, .players-card {
  background: rgba(26, 26, 46, 0.8);
  border-radius: 15px;
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.1);
  padding: 20px;
}

.status-title, .players-title {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 1.2rem;
  color: #4cc9f0;
  border-bottom: 1px solid rgba(76, 201, 240, 0.3);
  padding-bottom: 8px;
}

.status-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-label {
  font-size: 0.9rem;
  color: rgba(255, 255, 255, 0.7);
}

.status-value {
  font-weight: 500;
  color: #e2e2e2;
}

.win-text {
  color: #4caf50;
}

.lose-text {
  color: #f44336;
}

.draw-text {
  color: #ffc107;
}

.your-turn-text {
  color: #4cc9f0;
}

.opponent-turn-text {
  color: #ff9800;
}

.x-text {
  color: #2196F3;
  font-weight: bold;
}

.o-text {
  color: #F44336;
  font-weight: bold;
}

.players-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.player-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.05);
  transition: all 0.3s ease;
}

.player-item.current-player {
  background: rgba(76, 201, 240, 0.1);
  border-left: 3px solid #4cc9f0;
}

.player-item.you {
  background: rgba(106, 17, 203, 0.1);
}

.player-symbol {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-right: 10px;
}

.player-name {
  flex: 1;
}

.host-badge, .you-badge {
  font-size: 0.7rem;
  padding: 2px 6px;
  border-radius: 10px;
  margin-left: 8px;
}

.host-badge {
  background: rgba(76, 201, 240, 0.2);
  color: #4cc9f0;
}

.you-badge {
  background: rgba(106, 17, 203, 0.2);
  color: #6a11cb;
}

/* 移动端菜单项 */
.mobile-menu-items {
  padding: 15px;
}

.mobile-menu-items button {
  display: block;
  width: 100%;
  padding: 12px;
  margin-bottom: 10px;
  background: rgba(255, 255, 255, 0.1);
  border: none;
  border-radius: 8px;
  color: white;
  text-align: left;
  font-size: 16px;
}

.mobile-menu-items button.active {
  background: rgba(52, 152, 219, 0.3);
}

.mobile-menu-items i {
  margin-right: 10px;
}

/* 游戏规则内容 */
.rules-content {
  padding: 10px;
}

.rules-content h3 {
  color: #4cc9f0;
  margin-top: 15px;
}

.rules-content ol, .rules-content ul {
  padding-left: 20px;
}

.rules-content li {
  margin-bottom: 8px;
}

/* 在样式中添加中间棋盘的特殊样式 */
.small-board:nth-child(5) {
  position: relative;
  overflow: hidden;
}

.small-board:nth-child(5)::before {
  content: "🚫首步禁用";
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #ff4757;
  font-size: 0.8em;
  text-align: center;
  z-index: 1;
  opacity: 0.8;
  display: none;
}

/* 仅在首步时显示提示 */
.is-first-move .small-board:nth-child(5)::before {
  display: block;
}

.highlight-board {
  box-shadow: 0 0 0 3px rgba(79, 255, 157, 0.9);
  animation: pulse 1s infinite;
}

.highlight-ultimateboard {
  box-shadow: 0 0 0 3px rgba(79, 255, 157, 0.9);
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0%,100% {
    box-shadow: 0 0 0 0 rgba(46, 204, 113, 0.7);
  }
  70% {
    box-shadow: 0 0 0 8px rgba(46, 204, 113, 0.5);
  }

}

/* 移动端适配 */
@media (max-width: 767px) {
  .ultimate-tic-tac-toe-game {
    padding: 0;
    height: 100%;
    width: 100vw;
  }

  .grid-container {
    grid-template-columns: 1fr;
    grid-template-rows: 1fr;
    grid-template-areas: "game";
    padding: 15px;
    padding-top: 75px;
  }

  .user-panel {
    position: fixed;
    top: 60px;
    left: 0;
    bottom: 0;
    width: 280px;
    transform: translateX(-100%);
    z-index: 20;
  }

  .user-panel.mobile-active {
    transform: translateX(0);
  }

  .chat-panel, .status-panel {
    display: none;
    position: fixed;
    top: 60px;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(26, 26, 46, 0.95);
    z-index: 10;
    padding: 20px;
    overflow-y: auto;
  }

  .game-panel {
    min-height: calc(100vh - 90px);
  }

  .ultimate-board {
    width: 100%;
    max-width: 100%;
    aspect-ratio: 1/1;
  }

  .small-board {
    gap: 1px;
    padding: 2px;
  }

  .cell-content {
    font-size: 1rem;
  }

  .panel-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .game-info-display {
    flex-wrap: wrap;
  }

  .header-right {
    width: 100%;
    justify-content: flex-end;
    display: flex;
  }
}

/* 平板适配 */
@media (min-width: 768px) and (max-width: 1023px) {
  .grid-container {
    grid-template-columns: 250px 1fr;
    grid-template-areas: "user game";
  }

  .chat-panel, .status-panel {
    display: none;
  }
}
</style>
